/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Input, message, Popconfirm } from 'antd';
import type { StringObjType } from '@/components/_pages/AmountApply/index.d';
import type { ConnectState } from '@/models/connect';
import { usePageTabsChange } from '@/utils/hooks/pageTabs';
import { useRangePicker } from '@/utils/hooks/rangePicker';
import { getWkdInvoiceList, openInvoiceMutil } from '@/services/finance_receipt';
import type { Key } from 'antd/es/table/interface';
import styles from './index.less';
import { getColumns } from './utils';
import { electronicInvoice, useOperationWkd } from './hooks';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useSelector } from 'umi';
// import AsyncDownLoad from './AsyncDownload';
import QueryString from 'qs';
import moment from 'moment';

const ReceiptTemplateWkd: React.FC<{ activeKey: boolean; source: string }> = (props) => {
  const { activeKey, source } = props;
  const [show] = usePageTabsChange();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [selectList, setSelectList] = useState<Key[]>();
  const [wkdOperatonStatus, setWkdOperatonStatus] = useState<string>('1');
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [firstLoad, setFirstLoad] = useState<boolean>(false);

  const RangePicker = useRangePicker({
    title: '选择日期',
    valuesKeys: ['s_date', 'e_date'],
    defaultRange: 30,
    limitValueRange: 180,
  });

  const refreshList = useCallback(() => {
    setSelectList([]);
    actionRef.current?.reload();
  }, [actionRef]);

  const operationWkdUse = useOperationWkd({
    width: winSize == 'xs' ? 80 : 120,
    fixed: 'right',
    refreshList: refreshList,
    wkdOperatonStatus,
  });

  const isShowInvoice = useMemo(() => ['1', '4'].includes(wkdOperatonStatus), [wkdOperatonStatus]);

  useEffect(() => {
    if (show && activeKey) {
      refreshList();
    }
  }, [show, activeKey]);

  const wkdcolumns: ProColumns<StringObjType>[] = useMemo(
    () => [
      RangePicker,
      {
        title: '开票状态',
        hideInTable: true,
        dataIndex: 'status',
        valueType: 'select',
        initialValue: '1',
        valueEnum: {
          '1': { text: '待开票' },
          '2': { text: '开票中' },
          '3': { text: '开票失败' },
          '4': { text: '开票成功' },
          '5': { text: '已作废' },
        },
        fieldProps: {
          allowClear: false,
        },
      },
      {
        title: '开票来源',
        hideInTable: true,
        hideInSearch: source === 'jdk',
        dataIndex: 'source',
        valueType: 'select',
        initialValue: '',
        valueEnum: {
          '': { text: '全部' },
          wkd: { text: '微快递' },
          regiment: { text: '全寄' },
        },
        fieldProps: {
          allowClear: false,
        },
      },
      {
        title: '',
        hideInTable: true,
        dataIndex: 'keyword',
        renderFormItem: () => {
          return <Input name='keyword' placeholder='输入申请人手机号或抬头' />;
        },
      },
      ...getColumns(source),
      electronicInvoice({
        width: 80,
        fixed: winSize !== 'xs' ? 'right' : undefined,
        title: '电子发票',
        dataIndex: 'gd_pdf_url',
      }),
      operationWkdUse,
    ],
    [RangePicker, operationWkdUse],
  );

  const onFinish = async (params: StringObjType) => {
    const { code, data, msg } = await getWkdInvoiceList({ source, ...params });
    if (code == 0) {
      setWkdOperatonStatus(params.status);
      const { result, ...rest } = data;
      return {
        data: result,
        ...rest,
      };
    }
    if (code != 0) {
      message.error(msg);
    }
    setFirstLoad(true);
    return {};
  };

  const onOpenInvoiceMutil = async () => {
    const { code, msg } = await openInvoiceMutil({ id_str: selectList?.join(',') || '', source });
    if (code == 0) {
      message.info('成功');
      refreshList();
    }
    if (code != 0) {
      message.error(msg);
    }
  };

  const onDownload = () => {
    const { status, keyword = '', dates = [] } = formRef.current?.getFieldsValue();
    const query = QueryString.stringify({
      status,
      keyword,
      s_date: moment(dates[0]).format('YYYY-MM-DD'),
      e_date: moment(dates[1]).format('YYYY-MM-DD'),
      source,
    });
    window.open('/InvoiceManage/downloadExcel?' + query, '_self');
  };

  return (
    <DragTable>
      <ProTable<StringObjType>
        className={`kb-pro-table ${styles.receipt}`}
        actionRef={actionRef}
        formRef={formRef}
        rowKey='id'
        request={onFinish}
        columns={wkdcolumns}
        options={false}
        scroll={{ x: 2560 }}
        manualRequest={firstLoad}
        rowSelection={
          isShowInvoice
            ? {
                // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                // 注释该行则默认不显示下拉选项
                // selections: isShowInvoice ? [Table.SELECTION_ALL, Table.SELECTION_INVERT] : [],
                onChange: (ids) => setSelectList(ids),
                selectedRowKeys: selectList,
              }
            : false
        }
        pagination={{
          pageSize: 20,
          showSizeChanger: false,
        }}
        search={{
          collapseRender: () => <></>,
          collapsed: false,
          optionRender: (_, __, dom) => [
            ...dom.reverse(),
            // <AsyncDownLoad
            //   key='daownload'
            //   action={'/InvoiceManage/downloadExcel'}
            //   data={onDownload}
            // >
            //   <Button key='phone' type='primary' style={{ marginLeft: 20 }}>
            //     下载
            //   </Button>
            // </AsyncDownLoad>,
            <Button key='download' type='primary' style={{ marginLeft: 20 }} onClick={onDownload}>
              下载
            </Button>,
            isShowInvoice && (
              <Button key='phone' type='primary' disabled={!(selectList && selectList.length != 0)}>
                <Popconfirm key='mutil' title='确定批量开票？' onConfirm={onOpenInvoiceMutil}>
                  批量开票
                </Popconfirm>
              </Button>
            ),
          ],
        }}
      />
    </DragTable>
  );
};

export default ReceiptTemplateWkd;
